<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文章编辑器 - 我的博客</title>
    <link rel="stylesheet" href="assets/css/font-awesome.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f5f7fa;
            color: #333;
            line-height: 1.6;
        }

        /* 顶部导航 */
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 1rem;
            position: sticky;
            top: 0;
            z-index: 1000;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .header-content {
            max-width: 1200px;
            margin: 0 auto;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .header-title {
            font-size: 1.5rem;
            font-weight: 600;
        }

        .header-actions {
            display: flex;
            gap: 1rem;
        }

        .btn {
            padding: 0.5rem 1rem;
            border: none;
            border-radius: 6px;
            font-size: 0.9rem;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
        }

        .btn-outline {
            background: transparent;
            color: white;
            border: 2px solid rgba(255,255,255,0.3);
        }

        .btn-outline:hover {
            background: rgba(255,255,255,0.1);
            border-color: white;
        }

        .btn-primary {
            background: #28a745;
            color: white;
        }

        .btn-primary:hover {
            background: #218838;
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn-secondary:hover {
            background: #5a6268;
        }

        .btn-danger {
            background: #dc3545;
            color: white;
        }

        .btn-danger:hover {
            background: #c82333;
        }

        /* 编辑器容器 */
        .editor-container {
            max-width: 1200px;
            margin: 2rem auto;
            padding: 0 1rem;
        }

        .editor-form {
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .form-section {
            padding: 2rem;
            border-bottom: 1px solid #e9ecef;
        }

        .form-section:last-child {
            border-bottom: none;
        }

        .form-group {
            margin-bottom: 1.5rem;
        }

        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 600;
            color: #495057;
        }

        .form-control {
            width: 100%;
            padding: 0.75rem;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            font-size: 1rem;
            transition: border-color 0.3s ease;
        }

        .form-control:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102,126,234,0.1);
        }

        .textarea-large {
            min-height: 400px;
            resize: vertical;
            font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
        }

        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1rem;
        }

        .select-control {
            position: relative;
        }

        .select-control select {
            appearance: none;
            background: white url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='m6 8 4 4 4-4'/%3e%3c/svg%3e") no-repeat right 0.75rem center/16px 16px;
        }

        /* 标签输入 */
        .tag-input-container {
            position: relative;
        }

        .tag-list {
            display: flex;
            flex-wrap: wrap;
            gap: 0.5rem;
            margin-top: 0.5rem;
        }

        .tag {
            background: #667eea;
            color: white;
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.8rem;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
        }

        .tag-remove {
            cursor: pointer;
            background: rgba(255,255,255,0.3);
            border-radius: 50%;
            width: 16px;
            height: 16px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
        }

        .tag-remove:hover {
            background: rgba(255,255,255,0.5);
        }

        /* 预览区域 */
        .preview-container {
            max-height: 400px;
            overflow-y: auto;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            padding: 1rem;
            background: #fafbfc;
        }

        /* 操作按钮区域 */
        .editor-actions {
            padding: 1.5rem 2rem;
            background: #f8f9fa;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 1rem;
        }

        .action-group {
            display: flex;
            gap: 1rem;
            align-items: center;
        }

        .status-indicator {
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 500;
        }

        .status-draft {
            background: #ffc107;
            color: #000;
        }

        .status-published {
            background: #28a745;
            color: white;
        }

        .status-hidden {
            background: #6c757d;
            color: white;
        }

        /* 加载状态 */
        .loading {
            text-align: center;
            padding: 2rem;
            color: #6c757d;
        }

        .spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid #667eea;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 1rem;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .form-row {
                grid-template-columns: 1fr;
            }
            
            .header-content {
                flex-direction: column;
                gap: 1rem;
            }

            .header-actions {
                order: -1;
                width: 100%;
                justify-content: space-between;
            }

            .editor-actions {
                flex-direction: column;
                align-items: stretch;
            }

            .action-group {
                justify-content: center;
            }
        }

        /* 辅助样式 */
        .text-muted {
            color: #6c757d;
            font-size: 0.9rem;
        }

        .mb-3 {
            margin-bottom: 1rem;
        }

        .alert {
            padding: 0.75rem 1rem;
            margin-bottom: 1rem;
            border-radius: 6px;
            font-size: 0.9rem;
        }

        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .alert-danger {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .alert-warning {
            background: #fff3cd;
            color: #856404;
            border: 1px solid #ffeaa7;
        }
    </style>
</head>
<body>
    <!-- 顶部导航 -->
    <header class="header">
        <div class="header-content">
            <div class="header-title">
                <i class="fas fa-edit"></i>
                文章编辑器
            </div>
            <div class="header-actions">
                <a href="my-articles.html" class="btn btn-outline">
                    <i class="fas fa-list"></i>
                    我的文章
                </a>
                <a href="blog.html" class="btn btn-outline">
                    <i class="fas fa-home"></i>
                    返回首页
                </a>
            </div>
        </div>
    </header>

    <!-- 编辑器容器 -->
    <div class="editor-container">
        <div id="loadingIndicator" class="loading" style="display: none;">
            <div class="spinner"></div>
            <p>加载中...</p>
        </div>

        <div id="alertContainer"></div>

        <form class="editor-form" id="articleForm">
            <!-- 基本信息 -->
            <div class="form-section">
                <div class="form-group">
                    <label for="title">文章标题 *</label>
                    <input type="text" class="form-control" id="title" name="title" 
                           placeholder="请输入文章标题..." required>
                </div>

                <div class="form-group">
                    <label for="summary">文章摘要</label>
                    <textarea class="form-control" id="summary" name="summary" rows="3"
                              placeholder="请输入文章摘要（可选）..."></textarea>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label for="categoryId">分类</label>
                        <div class="select-control">
                            <select class="form-control" id="categoryId" name="categoryId">
                                <option value="">选择分类...</option>
                            </select>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="coverImage">封面图片URL</label>
                        <input type="url" class="form-control" id="coverImage" name="coverImage" 
                               placeholder="https://example.com/image.jpg">
                    </div>
                </div>

                <div class="form-group">
                    <label for="tagInput">标签</label>
                    <input type="text" class="form-control" id="tagInput" 
                           placeholder="输入标签名称，按回车添加...">
                    <div class="text-muted mb-3">输入标签名称并按回车键添加</div>
                    <div class="tag-list" id="tagList"></div>
                </div>
            </div>

            <!-- 内容编辑 -->
            <div class="form-section">
                <div class="form-group">
                    <label for="content">文章内容 *</label>
                    <div class="text-muted mb-3">支持Markdown语法</div>
                    <textarea class="form-control textarea-large" id="content" name="content" 
                              placeholder="请输入文章内容... 支持Markdown语法" required></textarea>
                </div>

                <div class="form-group" id="previewSection" style="display: none;">
                    <label>内容预览</label>
                    <div class="preview-container" id="contentPreview"></div>
                </div>
            </div>

            <!-- 操作按钮 -->
            <div class="editor-actions">
                <div class="action-group">
                    <span class="status-indicator" id="statusIndicator">草稿</span>
                    <button type="button" class="btn btn-secondary" id="previewBtn">
                        <i class="fas fa-eye"></i>
                        预览
                    </button>
                </div>

                <div class="action-group">
                    <button type="button" class="btn btn-secondary" id="saveDraftBtn">
                        <i class="fas fa-save"></i>
                        保存草稿
                    </button>
                    <button type="button" class="btn btn-primary" id="publishBtn">
                        <i class="fas fa-paper-plane"></i>
                        发布文章
                    </button>
                </div>
            </div>
        </form>
    </div>

    <script>
        // 全局变量
        let currentArticleId = null;
        let selectedTags = [];
        let isPreviewMode = false;

        // 页面初始化
        document.addEventListener('DOMContentLoaded', function() {
            console.log('文章编辑器页面初始化');
            
            if (!checkAuth()) {
                return;
            }

            initializeEditor();
        });

        // 检查登录状态
        function checkAuth() {
            const user = localStorage.getItem('user');
            const token = localStorage.getItem('token');
            
            if (!user || !token) {
                alert('请先登录');
                window.location.href = 'login.html';
                return false;
            }

            // 检查token是否过期
            if (isTokenExpired(token)) {
                alert('登录已过期，请重新登录');
                clearAuthData();
                window.location.href = 'login.html';
                return false;
            }

            return true;
        }

        // 检查token是否过期
        function isTokenExpired(token) {
            try {
                const payload = JSON.parse(atob(token.split('.')[1]));
                const currentTime = Date.now() / 1000;
                return payload.exp < currentTime;
            } catch (e) {
                console.error('解析token失败:', e);
                return true;
            }
        }

        // 清除认证数据
        function clearAuthData() {
            localStorage.removeItem('user');
            localStorage.removeItem('token');
            localStorage.removeItem('refreshToken');
            localStorage.removeItem('userRoles');
            localStorage.removeItem('userPermissions');
        }

        // 初始化编辑器
        async function initializeEditor() {
            // 检查URL参数，判断是编辑还是新建
            const urlParams = new URLSearchParams(window.location.search);
            const articleId = urlParams.get('id');

            if (articleId) {
                currentArticleId = articleId;
                await loadArticle(articleId);
                document.querySelector('.header-title').innerHTML = 
                    '<i class="fas fa-edit"></i> 编辑文章';
            }

            // 加载分类和标签数据
            await loadCategories();
            await loadTags();

            // 绑定事件
            bindEvents();
        }

        // 绑定事件
        function bindEvents() {
            // 标签输入
            document.getElementById('tagInput').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    addTag(this.value.trim());
                    this.value = '';
                }
            });

            // 预览按钮
            document.getElementById('previewBtn').addEventListener('click', togglePreview);

            // 保存草稿
            document.getElementById('saveDraftBtn').addEventListener('click', () => saveArticle(0));

            // 发布文章
            document.getElementById('publishBtn').addEventListener('click', () => saveArticle(1));

            // 自动保存草稿（每30秒）
            setInterval(autoSave, 30000);
        }

        // 加载文章详情
        async function loadArticle(articleId) {
            showLoading(true);
            
            try {
                const response = await fetchWithAuth(`/api/user/articles/${articleId}`);
                
                if (response.ok) {
                    const result = await response.json();
                    if (result.code === 0) {
                        const article = result.data;
                        
                        // 填充表单
                        document.getElementById('title').value = article.title || '';
                        document.getElementById('summary').value = article.summary || '';
                        document.getElementById('content').value = article.content || '';
                        document.getElementById('categoryId').value = article.categoryId || '';
                        document.getElementById('coverImage').value = article.coverImage || '';

                        // 设置状态指示器
                        updateStatusIndicator(article.status);

                        // 加载文章标签
                        if (article.tags && article.tags.length > 0) {
                            selectedTags = article.tags.map(tag => tag.name);
                            updateTagDisplay();
                        }
                    } else {
                        showAlert('加载文章失败：' + result.message, 'danger');
                    }
                } else {
                    showAlert('加载文章失败，请稍后重试', 'danger');
                }
            } catch (error) {
                console.error('加载文章失败:', error);
                showAlert('加载文章失败：' + error.message, 'danger');
            } finally {
                showLoading(false);
            }
        }

        // 加载分类列表
        async function loadCategories() {
            try {
                const response = await fetchWithAuth('/api/user/articles/categories');
                
                if (response.ok) {
                    const result = await response.json();
                    if (result.code === 0) {
                        const select = document.getElementById('categoryId');
                        result.data.forEach(category => {
                            const option = document.createElement('option');
                            option.value = category.id;
                            option.textContent = category.name;
                            select.appendChild(option);
                        });
                    }
                }
            } catch (error) {
                console.error('加载分类失败:', error);
            }
        }

        // 加载标签列表（用于提示）
        async function loadTags() {
            try {
                const response = await fetchWithAuth('/api/user/articles/tags');
                
                if (response.ok) {
                    const result = await response.json();
                    if (result.code === 0) {
                        // 可以用于标签自动完成功能（后续实现）
                        console.log('可用标签:', result.data);
                    }
                }
            } catch (error) {
                console.error('加载标签失败:', error);
            }
        }

        // 添加标签
        function addTag(tagName) {
            if (!tagName) return;
            
            if (selectedTags.includes(tagName)) {
                showAlert('标签已存在', 'warning');
                return;
            }

            if (selectedTags.length >= 5) {
                showAlert('最多只能添加5个标签', 'warning');
                return;
            }

            selectedTags.push(tagName);
            updateTagDisplay();
        }

        // 删除标签
        function removeTag(tagName) {
            selectedTags = selectedTags.filter(tag => tag !== tagName);
            updateTagDisplay();
        }

        // 更新标签显示
        function updateTagDisplay() {
            const tagList = document.getElementById('tagList');
            tagList.innerHTML = '';

            selectedTags.forEach(tagName => {
                const tagElement = document.createElement('span');
                tagElement.className = 'tag';
                tagElement.innerHTML = `
                    ${tagName}
                    <span class="tag-remove" onclick="removeTag('${tagName}')">×</span>
                `;
                tagList.appendChild(tagElement);
            });
        }

        // 切换预览模式
        function togglePreview() {
            const previewSection = document.getElementById('previewSection');
            const previewBtn = document.getElementById('previewBtn');
            const contentTextarea = document.getElementById('content');

            if (isPreviewMode) {
                previewSection.style.display = 'none';
                previewBtn.innerHTML = '<i class="fas fa-eye"></i> 预览';
                isPreviewMode = false;
            } else {
                const content = contentTextarea.value;
                const previewContainer = document.getElementById('contentPreview');
                
                // 简单的Markdown到HTML转换（基础实现）
                previewContainer.innerHTML = markdownToHtml(content);
                previewSection.style.display = 'block';
                previewBtn.innerHTML = '<i class="fas fa-eye-slash"></i> 隐藏预览';
                isPreviewMode = true;
            }
        }

        // 简单的Markdown转HTML（基础实现）
        function markdownToHtml(markdown) {
            return markdown
                .replace(/^### (.*$)/gim, '<h3>$1</h3>')
                .replace(/^## (.*$)/gim, '<h2>$1</h2>')
                .replace(/^# (.*$)/gim, '<h1>$1</h1>')
                .replace(/\*\*(.*?)\*\*/gim, '<strong>$1</strong>')
                .replace(/\*(.*?)\*/gim, '<em>$1</em>')
                .replace(/^\> (.*$)/gim, '<blockquote>$1</blockquote>')
                .replace(/\n\n/gim, '</p><p>')
                .replace(/^(.*)$/gim, '<p>$1</p>');
        }

        // 保存文章
        async function saveArticle(status) {
            const form = document.getElementById('articleForm');
            const formData = new FormData(form);

            // 验证必填字段
            if (!formData.get('title').trim()) {
                showAlert('请输入文章标题', 'danger');
                return;
            }

            if (!formData.get('content').trim()) {
                showAlert('请输入文章内容', 'danger');
                return;
            }

            const articleData = {
                title: formData.get('title').trim(),
                summary: formData.get('summary').trim(),
                content: formData.get('content').trim(),
                categoryId: formData.get('categoryId') ? parseInt(formData.get('categoryId')) : null,
                coverImage: formData.get('coverImage').trim() || null,
                status: status,
                tags: selectedTags
            };

            showLoading(true);

            try {
                let response;
                if (currentArticleId) {
                    // 更新文章
                    response = await fetchWithAuth(`/api/user/articles/${currentArticleId}`, {
                        method: 'PUT',
                        body: JSON.stringify(articleData)
                    });
                } else {
                    // 创建文章
                    response = await fetchWithAuth('/api/user/articles', {
                        method: 'POST',
                        body: JSON.stringify(articleData)
                    });
                }

                if (response.ok) {
                    const result = await response.json();
                    if (result.code === 0) {
                        const statusText = status === 1 ? '发布' : '保存草稿';
                        showAlert(`文章${statusText}成功！`, 'success');
                        
                        // 如果是新建文章，更新当前文章ID
                        if (!currentArticleId && result.data && result.data.id) {
                            currentArticleId = result.data.id;
                            // 更新URL
                            const newUrl = `${window.location.pathname}?id=${currentArticleId}`;
                            window.history.replaceState({}, '', newUrl);
                        }

                        updateStatusIndicator(status);
                    } else {
                        showAlert('保存失败：' + result.message, 'danger');
                    }
                } else {
                    showAlert('保存失败，请稍后重试', 'danger');
                }
            } catch (error) {
                console.error('保存文章失败:', error);
                showAlert('保存失败：' + error.message, 'danger');
            } finally {
                showLoading(false);
            }
        }

        // 自动保存草稿
        async function autoSave() {
            const title = document.getElementById('title').value.trim();
            const content = document.getElementById('content').value.trim();

            if (title && content) {
                console.log('自动保存草稿...');
                await saveArticle(0);
            }
        }

        // 更新状态指示器
        function updateStatusIndicator(status) {
            const indicator = document.getElementById('statusIndicator');
            
            indicator.className = 'status-indicator';
            
            if (status === 1) {
                indicator.classList.add('status-published');
                indicator.textContent = '已发布';
            } else if (status === 2) {
                indicator.classList.add('status-hidden');
                indicator.textContent = '已隐藏';
            } else {
                indicator.classList.add('status-draft');
                indicator.textContent = '草稿';
            }
        }

        // 创建带认证头的fetch请求
        function fetchWithAuth(url, options = {}) {
            const token = localStorage.getItem('token');
            
            options.headers = {
                ...options.headers,
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            };
            
            return fetch(url, options);
        }

        // 显示加载状态
        function showLoading(show) {
            const loading = document.getElementById('loadingIndicator');
            loading.style.display = show ? 'block' : 'none';
        }

        // 显示提示信息
        function showAlert(message, type) {
            const container = document.getElementById('alertContainer');
            const alert = document.createElement('div');
            alert.className = `alert alert-${type}`;
            alert.textContent = message;
            
            container.appendChild(alert);
            
            // 3秒后自动消失
            setTimeout(() => {
                if (alert.parentNode) {
                    alert.parentNode.removeChild(alert);
                }
            }, 3000);
        }
    </script>
</body>
</html>
